<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Chat Test</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.6.1/sockjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
        }
        .container {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        .connection-panel, .message-panel {
            border: 1px solid #ccc;
            padding: 20px;
            border-radius: 5px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
        }
        input, textarea {
            width: 100%;
            padding: 8px;
            margin-bottom: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        button {
            padding: 10px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        button:disabled {
            background-color: #cccccc;
        }
        #messageDisplay {
            height: 300px;
            border: 1px solid #ddd;
            padding: 10px;
            overflow-y: auto;
            margin-bottom: 10px;
        }
        .message {
            margin: 5px 0;
            padding: 5px;
            border-radius: 4px;
        }
        .sent {
            background-color: #e3f2fd;
            margin-left: 20%;
        }
        .received {
            background-color: #f5f5f5;
            margin-right: 20%;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="connection-panel">
            <h2>Connection Settings</h2>
            <div class="form-group">
                <label for="token">Token:</label>
                <input type="text" id="token" placeholder="Enter your token">
            </div>
            <button id="connectBtn" onclick="connect()">Connect</button>
            <button id="disconnectBtn" onclick="disconnect()" disabled>Disconnect</button>
        </div>

        <div class="message-panel">
            <h2>Chat</h2>
            <div class="form-group">
                <label for="senderId">Sender ID:</label>
                <input type="number" id="senderId" placeholder="Enter sender ID">
            </div>
            <div class="form-group">
                <label for="receiverId">Receiver ID:</label>
                <input type="number" id="receiverId" placeholder="Enter receiver ID">
            </div>
            <div id="messageDisplay"></div>
            <div class="form-group">
                <label for="messageContent">Message:</label>
                <textarea id="messageContent" rows="3" placeholder="Type your message"></textarea>
            </div>
            <div class="form-group">
                <label for="files">Files:</label>
                <input type="file" id="files" multiple>
            </div>
            <button id="sendBtn" onclick="sendMessage()" disabled>Send Message</button>
        </div>
    </div>

    <script>
        let stompClient = null;

        function connect() {
            const token = document.getElementById('token').value;
            if (!token) {
                alert('Please enter a token');
                return;
            }

            const socket = new SockJS(`/chat?token=${token}`);
            stompClient = Stomp.over(socket);
            
            stompClient.connect({}, function(frame) {
                console.log('Connected: ' + frame);
                document.getElementById('connectBtn').disabled = true;
                document.getElementById('disconnectBtn').disabled = false;
                document.getElementById('sendBtn').disabled = false;

                // Subscribe to receive messages
                stompClient.subscribe('/queue/messages/' + document.getElementById('senderId').value + '&' + document.getElementById('receiverId').value, function(message) {
                    showMessage(JSON.parse(message.body), 'received');
                });
            }, function(error) {
                console.error('Connection error:', error);
                alert('Connection failed: ' + error);
            });
        }

        function disconnect() {
            if (stompClient !== null) {
                stompClient.disconnect();
                document.getElementById('connectBtn').disabled = false;
                document.getElementById('disconnectBtn').disabled = true;
                document.getElementById('sendBtn').disabled = true;
                console.log("Disconnected");
            }
        }

        function sendMessage() {
            const senderId = document.getElementById('senderId').value;
            const receiverId = document.getElementById('receiverId').value;
            const content = document.getElementById('messageContent').value;
            const files = document.getElementById('files').files;

            if (!senderId || !receiverId || !content) {
                alert('Please fill in all required fields');
                return;
            }

            // Create FormData for file upload
            const formData = new FormData();
            formData.append('senderId', senderId);
            formData.append('receiverId', receiverId);
            formData.append('content', content);
            
            for (let file of files) {
                formData.append('files', file);
            }

            // Send HTTP request for file upload
            fetch('/api/chat/sendMessage', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(result => {
                console.log('Upload result:', result);
                
                // Send WebSocket message
                const message = {
                    senderId: senderId,
                    receiverId: receiverId,
                    content: content,
                    timestamp: new Date()
                };
                
                stompClient.send("/app/sendWebSocketMessage", {}, JSON.stringify(message));
                showMessage(message, 'sent');
                
                // Clear inputs
                document.getElementById('messageContent').value = '';
                document.getElementById('files').value = '';
            })
            .catch(error => {
                console.error('Error:', error);
                alert('Error sending message: ' + error);
            });
        }

        function showMessage(message, type) {
            const messageDisplay = document.getElementById('messageDisplay');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}`;
            messageDiv.textContent = `${message.senderId} -> ${message.receiverId}: ${message.content}`;
            messageDisplay.appendChild(messageDiv);
            messageDisplay.scrollTop = messageDisplay.scrollHeight;
        }
    </script>
</body>
</html>